<?php
namespace backend\controllers;

use yii\web\AdminController;
use backend\models\UploadForm;
use Yii;
use backend\models\ContentArticleCategory;
use backend\models\ContentArticle;
use backend\models\GoodsIdentification;
use common\helps\tools;
use yii\web\NotFoundHttpException;

class ArticleController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'Article';
    //文章分类页
    public function actionCategory(){
        $model = new UploadForm();
        return $this->render('category',['model'=>$model]);
    }
    //获取文章分类信息
    public function actionGetArticleCategory(){
        $data = Yii::$app->request->post();
        $query = ContentArticleCategory::find()->select('id,category_title,sort,use_flg,is_display');
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])->orderBy(
            [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC])->asArray()->all();
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }
    //获取单个文章分类详情
    public function actionGetArticleCategoryDetail(){
        $data = Yii::$app->request->post();
        $result = ContentArticleCategory::find()->where('id=:id',[':id'=>$data['id']])->asArray()->one();
        $this->retJson($result,200);
    }
    //获取修改文章分类详情信息
    public function actionChangeArticleCategory(){
        $article_category = new ContentArticleCategory();
        $data = Yii::$app->request->post();
        try {
            $category_id = $data['category_id'];
            $category_title = $data['category_title'];
            $sort = $data['sort'];
            $category_pic = $data['category_pic'];
            $use_flg = $data['use_flg'];
            $is_display = $data['is_display'];
            $memo = $data['memo'];
            if (!$category_title) {
                throw new \Exception('请填写文章分类名称');
            }
            if (!$sort) {
                throw new \Exception('请填写文章分类排序编号');
            }
            if (!$category_pic) {
                throw new \Exception('请上传分类图片');
            }
            $creator = $article_category->getCreator();
            if ($category_id){
                $article_category = ContentArticleCategory::findOne($category_id);
                $article_category->editor = $creator;
                $article_category->edit_time = date('Y-m-d H:i:s',time());
            }else{
                $article_category->creator = $creator;
                $article_category->create_time = date('Y-m-d H:i:s',time());
            }
            $article_category->category_title = $category_title;
            $article_category->sort = $sort;
            $article_category->category_pic = $category_pic;
            $article_category->use_flg = $use_flg;
            $article_category->is_display = $is_display;
            $article_category->memo = $memo;
            $article_category->save();
            $article_category_id = $article_category->attributes['id'];
            if (!$article_category_id){
                throw new \Exception('操作失败，请重试');
            }
            $this->retJson('编辑成功',200);
        }catch (\Exception $e){
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
    //修改文章分类状态和首页显示状态
    public function actionChangeArticleCategoryStatus(){
        $article_category = new ContentArticleCategory();
        $data = Yii::$app->request->post();
        $type = $data['type'];
        $status = intval($data['status']);
        $data_now = $article_category_where = array();
        if ($type == 1){
            $data_now['use_flg'] = $status;
            if (!$status){
                $data_now['is_display'] = 0;
            }
        }else{
            $data_now['is_display'] = $status;
        }
        $data_now['editor'] = $article_category->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $article_category_where = ['id'=>$data['id']];
        $ret = $article_category::updateAll($data_now,$article_category_where);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $this->retJson('操作成功',200);
    }
    //文章维护列表页
    public function actionIndex(){
        $model = new UploadForm();
        //商品标识
        $where = [
            'and',
            ['use_flg'=>1],
            ['in','type',[2,3]]
        ];
        $goods_identification = GoodsIdentification::find()->where($where)->asArray()->all();
        //文章分类
        $article_category = ContentArticleCategory::find()->where('use_flg=1')->asArray()->all();
        return $this->render('index',['article_category'=>$article_category,'goods_identification'=>$goods_identification,'model'=>$model]);
    }
    //获取文章信息
    public function actionGetArticle(){
        $data = Yii::$app->request->post();
        $query = ContentArticle::find()->select('id,article_title,sort,use_flg,category_id,is_release,article_classification,article_link');
        $article_title = trim($data['article_title']);
        if ($article_title){
            $query = $query->where(['like','article_title',$article_title]);
        }
        if ($data['category_id']){
            $query = $query->andWhere('category_id=:category_id',[':category_id'=>$data['category_id']]);
        }
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])->orderBy(
            [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC]
        )->asArray()->all();
        $list_new = array();
        if (count($list) > 0){
            $category_ids = array_column($list, 'category_id');
            if (count($category_ids) > 0){
                $article_category = ContentArticleCategory::find()->where(['in','id',$category_ids])->asArray()->all();
                $article_category_new = array_combine(array_column($article_category, 'id'),$article_category);
                array_merge($article_category,$article_category_new);
                foreach ($list as $article){
                    $article['category_title'] = $article_category_new[$article['category_id']]['category_title'];
                    $list_new[] = $article;
                }
            }
        }
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list_new;
        return \yii\helpers\Json::encode($result);
    }
    //文章启用禁用
    public function actionChangeArticleStatus()
    {
        $data_now = array();
        $model = new ContentArticle();
        $data = Yii::$app->request->post();
        $type = $data['type'];
        $status = $data['status'];
        if ($type == 1){
            $data_now['use_flg'] = $status;
            if (!$status){
                $data_now['is_release'] = 0;
            }
        }else{
            $data_now['is_release'] = $status;
            if ($status == '1'){
                $article_data = $model->find()->select('description')->where(['id'=>$data['id']])->one();
                $data_now['formal_description'] = $article_data['description'];
            }
        }
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $article_where = ['id'=>$data['id']];
        $ret = $model::updateAll($data_now,$article_where);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $this->retJson('操作成功',200);
    }
    //获取文章详情信息
    public function actionGetArticleDetail(){
        $data = Yii::$app->request->post();
        $where = ['id'=>$data['id']];
        $result = ContentArticle::find()->where($where)->asArray()->one();
        $this->retJson($result,200);
    }
    //修改文章分类详情信息
    public function actionChangeArticle(){
        $article = new ContentArticle();
        $data = Yii::$app->request->post();
        try {
            $article_id = $data['article_id'];
            $article_category_id = $data['category_id'];
            if (!$article_category_id) {
                throw new \Exception('清选择文章分类');
            }
            $article_title = $data['article_title'];
            if (!$article_title) {
                throw new \Exception('请填写文章标题');
            }
            $sort = $data['sort'];
            if (!$sort) {
                throw new \Exception('请填写排序编号');
            }
            $article_link = $data['article_link'];
            $article_pic = $data['article_pic'];
            $content = $data['content'];
            if (!$content && !$article_link) {
                throw new \Exception('外部链接或文章内容必须填写一项');
            }
//             if (!tools::arrayHasValue($data,'article_detail_pic') || count(array_filter($data['article_detail_pic'])) == 0){
//                 throw new \Exception('请至少上传一张文章详情图片');
//             }
            $article_detail_pic = tools::arrayHasValue($data,'article_detail_pic') ? array_filter($data['article_detail_pic']) : '';
            $summary = $data['summary'];
            $use_flg = $data['use_flg'];
            $article_classification = $data['article_classification'];
            $article_identification = $data['article_identification'];
            if ($article_identification){
                $where = [
                    'and',
                    ['type'=>3],
                    ['id'=>$article_identification]
                ];
                $goods_identification = GoodsIdentification::find()->where($where)->asArray()->one();
                if (tools::arrayHasValue($goods_identification,'id') && $goods_identification['use_flg'] != '1'){
                    throw new \Exception('标识【'.$goods_identification['name'].'】已停用，请确认');
                }elseif (!tools::arrayHasValue($goods_identification,'id')){
                    throw new \Exception('文章标识不存在，请联系技术');
                }
            }
            $video_url_pc = $data['video_url_pc'];
            $video_url_wap = $data['video_url_wap'];
            $oper = $article->getCreator();
            $operTime = date('Y-m-d H:i:s',time());
            if ($article_id){
                $article = ContentArticle::findOne($article_id);
                $article->editor = $oper;
                $article->edit_time = $operTime;
            }else{
                $article->creator = $oper;
                $article->create_time = $operTime;
            }
            if (!$article_id || ($article_id && $article->description != $content)){
                $article->is_release = 0;
            }
            $article->article_title = $article_title;
            $article->category_id = $article_category_id;
            $article->sort = $sort;
            $article->article_link = $article_link;
            $article->article_pic = $article_pic;
            $article->summary = $summary;
            $article->description = $content;
            $article->use_flg = $use_flg;
            $article->article_detail_pic = json_encode($article_detail_pic);
            $article->article_classification = $article_classification;
            $article->article_identification = $article_identification;
            $article->video_url_pc = $video_url_pc;
            $article->video_url_wap = $video_url_wap;
            $article->save();
            $id = $article->attributes['id'];
            if (!$id){
                throw new \Exception('文章信息操作失败');
            }
            $this->retJson('操作成功',200);
        } catch (\Exception $e) {
            $this->retJson($e->getMessage(),500);
        }
    }
    
    public function actionPreview(){
        $this->layout = 'main_pro';
        $data = Yii::$app->request->get();
        if (!tools::arrayHasValue($data,'type') || !$data['type']){
            throw new NotFoundHttpException('参数类型不存在',404);
        }
        if ($data['type'] == '1'){
            if (!tools::arrayHasValue($data,'id') || !$data['id']){
                throw new NotFoundHttpException('参数不存在',404);
            }
            //查询文章信息
            $article = ContentArticle::find()->where(['a.id'=>$data['id'],])->alias('a')->select('a.*,c.category_title')
            ->leftJoin('j_content_article_category as c','c.id = a.category_id')->asArray()->one();
            
            if(!$article){
                throw new NotFoundHttpException('文章信息不存在');
            }
            
            $view = tools::arrayHasValue($GLOBALS['_ARTICLE_LIST'],$data['id']) ? $GLOBALS['_ARTICLE_LIST'][$data['id']] : '';
            if (!$view){
                $view	= $GLOBALS['_ARTICLE_LIST'][ARTICLE_LIST_DEFAULT] ;
            }
            if ($view == 'news-center'){
                $news_classification = new GoodsIdentification();
                $news_classification = GoodsIdentification::find()->select('id,name')->where(
                    'type='.$news_classification::TYPE_NEWS
                )->asArray()->all();
                return $this->render('news-center',['news_classification'=>$news_classification]);
            }else{
                return $this->render($view,['article'=>$article]);
            }
        }else{
            if (!tools::arrayHasValue($data,'news_id') || !$data['news_id']){
                throw new NotFoundHttpException('参数不存在',404);
            }
            $news_detail = ContentArticle::find()->where(
                'id=:id',[':id'=>$data['news_id']]
            )->asArray()->one();
            if (!$news_detail){
                throw new NotFoundHttpException('新闻数据不存在',404);
            }
            if($news_detail['category_id'] == 6){
                return $this->render('article-detail',['news_detail'=>$news_detail]);
            }else{
                return $this->render('news-detail',['news_detail'=>$news_detail]);
            }
        }
    }
    
    /**
     * 预加载根据条件筛选获取新闻动态
     */
    public function actionGetNewsList(){
        $data = Yii::$app->request->post();
        $news_list = ContentArticle::find()->where(
            'category_id='.ARTICLE_CATEGORY_NEWS_DYNAMIC
            );
        if ($data['article_classification']){
            $news_list = $news_list->andWhere('article_classification=:article_classification',[':article_classification'=>$data['article_classification']]);
        }
        if ($data['news_date']){
            $news_list = $news_list->andWhere(['like','edit_time',$data['news_date']]);
        }
        $rows_perpage = 6;
        $page = $data['paging'];
        $page = ($page - 1) * $rows_perpage;
        $news_list = $news_list->offset($page)->limit($rows_perpage)->asArray()->all();
        $this->retJson($news_list, 200);
    }
}